package my.springboot.async;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import my.file.json.jackson.JsonUtil;

@Configuration
@EnableAsync
@ComponentScan("my.springboot.async")
public class App {
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
		AsyncWork bean = context.getBean(AsyncWork.class);
//		doWork(bean);
		doWorkResult(bean);
		context.close();
		
	}
	
	/**
	 * 无返回结果
	 * @param bean
//	 */
//	public static void doWork(AsyncService bean){
//		for (int i = 0; i < 5; i++) {
//			bean.doWork(i);
//		}
//	}
//
	/**
	 * 有返回结果
	 * @param bean
	 */
	public static void doWorkResult(AsyncWork bean){
		List<Future<Integer>>  doWorkResultList = new LinkedList<Future<Integer>>();
		for (int i = 0; i < 5; i++) {
			Future<Integer> doWorkResult = bean.doWorkResult(i);
			doWorkResultList.add(doWorkResult);
		}
		
		List<Integer> list = new ArrayList<Integer>(doWorkResultList.size());
		for (Future<Integer> future : doWorkResultList) {
			try {
				list.add(future.get());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
				list.add(0);
			}
		}
		System.out.println(JsonUtil.objToJson(list));
	}
}
